package com.mzj.saas.mservice.smartlock.service.tianwanghulian;

import cn.hutool.core.date.DateUtil;
import com.mzj.saas.commons.enums.LockAlarmTypeEnum;
import com.mzj.saas.mservice.lock.Repository.LockAlarmRepository;
import com.mzj.saas.mservice.lock.Repository.LockOpenLogRepository;
import com.mzj.saas.mservice.lock.Repository.SmartLockPwdRepository;
import com.mzj.saas.mservice.lock.Repository.SmartLockRepository;
import com.mzj.saas.mservice.lock.entity.LockAlarm;
import com.mzj.saas.mservice.lock.entity.LockOpenLog;
import com.mzj.saas.mservice.lock.entity.SmartLock;
import com.mzj.saas.mservice.lock.entity.SmartLockAuth;
import com.mzj.saas.mservice.smartlock.vo.tianwanghulian.TwhlCallBackVO;
import com.mzj.saas.mservice.smartlock.vo.tianwanghulian.TwhlDataVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 天网互联-事件回调处理
 */
@Service
public class SmartLockTwhlEventHandleService {

    private static final Logger log = LoggerFactory.getLogger(SmartLockTwhlEventHandleService.class);

    private static final String authSql = "SELECT a.id,a.user_name as userName  FROM saas_smart_lock_auth a "
            + "LEFT  JOIN  saas_smart_lock_pwd p ON a.id = p.lock_auth_id \n"
            + "WHERE p.identification  = ?";

    private static final String cardSql = "SELECT a.id,a.user_name AS userName FROM saas_smart_lock_auth a LEFT JOIN "
            + "saas_smart_lock_card c ON a.id = c.lock_auth_id WHERE c.identification = ?";

    private static final String fingerprintSql = "SELECT a.id,a.user_name AS userName FROM saas_smart_lock_auth a LEFT JOIN "
            + "saas_smart_lock_fingerprint f ON a.id = f.lock_auth_id WHERE  f.identification = ?";

    private static final String bleSql = "SELECT a.id,a.user_name AS userName FROM saas_smart_lock_auth a LEFT JOIN "
            + "saas_smart_lock_ble b ON a.id = b.lock_auth_id WHERE b.identification = ?";

    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private LockAlarmRepository lockAlarmRepository;
    @Autowired
    private SmartLockPwdRepository smartLockPwdRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private LockOpenLogRepository lockOpenLogRepository;

    /**
     * 心跳日志
     * @param vo
     */
    public String lockOnlineCallBack(TwhlCallBackVO vo) {
        TwhlDataVo data = vo.getData();
        Integer dataType = data.getDataType();
        if (dataType == 0) {
            SmartLock smartLock = smartLockRepository.findBySn(data.getDeviceNum());
            if (smartLock == null) {
                log.warn("天网互联-心跳日志, 数据库未找到设备信息, deviceId={}", vo.getData());
                //智能锁没有绑在房子上不用记录，直接返回ok
                return "ok";
            }
            Integer signalStrength = data.getSignalStrength();
            if (signalStrength >= 80) {
                smartLock.setSignalLevel(1);
            } else if (signalStrength >= 50 && signalStrength < 80) {
                smartLock.setSignalLevel(2);
            } else {
                smartLock.setSignalLevel(3);
            }
            smartLock.setElectricQuantity(data.getBattery());
            smartLockRepository.save(smartLock);
        }
        return "ok";
    }

    /**
     * 告警日志
     *
     * @param vo
     */
    public String lockAlarm(TwhlCallBackVO vo) {
        TwhlDataVo data = vo.getData();
        SmartLock smartLock = smartLockRepository.findBySn(data.getDeviceNum());
        if (smartLock == null) {
            log.warn("天网互联-告警日志, 数据库未找到设备信息, deviceId={}", vo.getData());
            //智能锁没有绑在房子上不用记录，直接返回ok
            return "ok";
        }
        LockAlarm lockAlarm = new LockAlarm();
        switch (data.getAlarmType()) {
            case 1://撞击报警
                return "ok";
            case 2:// 低电量
                lockAlarm.setAlarmType(LockAlarmTypeEnum.LOW.getValue());
                lockAlarm.setLockId(smartLock.getId());
                lockAlarm.setHouseId(smartLock.getHouseId());
                lockAlarm.setSn(smartLock.getSn());
                lockAlarm.setElectric(smartLock.getElectricQuantity());
                lockAlarm.setAlarmTime(new Date());
                lockAlarmRepository.save(lockAlarm);
                return "ok";
            case 3:// 撬锁报警
                lockAlarm.setAlarmType(LockAlarmTypeEnum.PICK_PROOF.getValue());
                lockAlarm.setLockId(smartLock.getId());
                lockAlarm.setHouseId(smartLock.getHouseId());
                lockAlarm.setSn(smartLock.getSn());
                lockAlarm.setElectric(smartLock.getElectricQuantity());
                lockAlarm.setAlarmTime(new Date());
                lockAlarmRepository.save(lockAlarm);
                return "ok";
            case 5:// 长时间未关
                return "ok";
            case 6:// 蓝牙cookie错误
                return "ok";
            case 8:// 非法开门报警
                lockAlarm.setAlarmType(LockAlarmTypeEnum.DURESS.getValue());
                lockAlarm.setLockId(smartLock.getId());
                lockAlarm.setHouseId(smartLock.getHouseId());
                lockAlarm.setSn(smartLock.getSn());
                lockAlarm.setElectric(smartLock.getElectricQuantity());
                lockAlarm.setAlarmTime(new Date());
                lockAlarmRepository.save(lockAlarm);
                return "ok";
            case 9:// 密码错误自锁报警
                lockAlarm.setAlarmType(LockAlarmTypeEnum.STRANGER.getValue());
                lockAlarm.setLockId(smartLock.getId());
                lockAlarm.setHouseId(smartLock.getHouseId());
                lockAlarm.setSn(smartLock.getSn());
                lockAlarm.setElectric(smartLock.getElectricQuantity());
                lockAlarm.setAlarmTime(new Date());
                lockAlarmRepository.save(lockAlarm);
                return "ok";
            default:
                return "ok";
        }
    }

    /**
     * 开锁日志
     *
     * @param vo
     */
    public String logEventHandle(TwhlCallBackVO vo) {
        TwhlDataVo data = vo.getData();
        SmartLock smartLock = smartLockRepository.findBySn(data.getDeviceNum());
        String identification = data.getIdentification();

        if (smartLock == null) {
            log.warn("天网互联-开锁日志, 数据库未找到设备信息, deviceId={}", vo.getData());
            //智能锁没有绑在房子上不用记录，直接返回ok
            return "ok";
        }
        // 开门记录
        LockOpenLog openLog = new LockOpenLog();
        switch (data.getUnlockType()) {
            case 2://指纹
                openLog.setLockId(smartLock.getId());
                openLog.setHouseId(smartLock.getHouseId());
                openLog.setOpenMode(21);
                openLog.setOpenType(1);// 开门类型：0未知 1外开门 2内开门
                openLog.setBuildName(smartLock.getBuildName());
                openLog.setCommunityName(smartLock.getCommunityName());
                openLog.setUnitName(smartLock.getUnitName());
                openLog.setMatchUserName(smartLock.getMatchUserName());
                openLog.setRoomNumber(smartLock.getRoomNumber());
                openLog.setOpenTime(DateUtil.parse(data.getUnlockTime()));
                openLog.setUserProperty(0);// 开门人性质：0未知 1承租人 2同住人
                SmartLockAuth smartLockAuth = jdbcTemplate.queryForObject(fingerprintSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), identification);
                openLog.setUserId(smartLockAuth.getId());
                openLog.setOpenUserName(smartLockAuth.getUserName());//开门人姓名
                lockOpenLogRepository.save(openLog);
                return "ok";
            case 3://临时密码
                openLog.setLockId(smartLock.getId());
                openLog.setHouseId(smartLock.getHouseId());
                openLog.setOpenMode(0);
                openLog.setOpenType(1);// 开门类型：0未知 1外开门 2内开门
                openLog.setBuildName(smartLock.getBuildName());
                openLog.setCommunityName(smartLock.getCommunityName());
                openLog.setUnitName(smartLock.getUnitName());
                openLog.setMatchUserName(smartLock.getMatchUserName());
                openLog.setRoomNumber(smartLock.getRoomNumber());
                openLog.setOpenTime(DateUtil.parse(data.getUnlockTime()));
                openLog.setUserProperty(0);// 开门人性质：0未知 1承租人 2同住人
                SmartLockAuth smartLockAuth1 = jdbcTemplate.queryForObject(authSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), identification);
                openLog.setUserId(smartLockAuth1.getId());
                openLog.setOpenUserName(smartLockAuth1.getUserName());//开门人姓名
                lockOpenLogRepository.save(openLog);
                return "ok";
            case 5://蓝牙开锁
                openLog.setLockId(smartLock.getId());
                openLog.setHouseId(smartLock.getHouseId());
                openLog.setOpenMode(25);
                openLog.setOpenType(1);// 开门类型：0未知 1外开门 2内开门
                openLog.setBuildName(smartLock.getBuildName());
                openLog.setCommunityName(smartLock.getCommunityName());
                openLog.setUnitName(smartLock.getUnitName());
                openLog.setMatchUserName(smartLock.getMatchUserName());
                openLog.setRoomNumber(smartLock.getRoomNumber());
                openLog.setOpenTime(DateUtil.parse(data.getUnlockTime()));
                openLog.setUserProperty(0);// 开门人性质：0未知 1承租人 2同住人
                SmartLockAuth smartLockAuth2 = jdbcTemplate.queryForObject(bleSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), identification);
                openLog.setUserId(smartLockAuth2.getId());
                openLog.setOpenUserName(smartLockAuth2.getUserName());//开门人姓名
                lockOpenLogRepository.save(openLog);
                return "ok";
            case 7://门卡开锁
                openLog.setLockId(smartLock.getId());
                openLog.setHouseId(smartLock.getHouseId());
                openLog.setOpenMode(11);
                openLog.setOpenType(1);// 开门类型：0未知 1外开门 2内开门
                openLog.setBuildName(smartLock.getBuildName());
                openLog.setCommunityName(smartLock.getCommunityName());
                openLog.setUnitName(smartLock.getUnitName());
                openLog.setMatchUserName(smartLock.getMatchUserName());
                openLog.setRoomNumber(smartLock.getRoomNumber());
                openLog.setOpenTime(DateUtil.parse(data.getUnlockTime()));
                openLog.setUserProperty(0);// 开门人性质：0未知 1承租人 2同住人
                SmartLockAuth smartLockAuth3 = jdbcTemplate.queryForObject(cardSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), identification);
                openLog.setUserId(smartLockAuth3.getId());
                openLog.setOpenUserName(smartLockAuth3.getUserName());//开门人姓名
                lockOpenLogRepository.save(openLog);
                return "ok";
            case 10://机械钥匙开门
                openLog.setLockId(smartLock.getId());
                openLog.setHouseId(smartLock.getHouseId());
                openLog.setOpenMode(30);
                openLog.setOpenType(2);// 开门类型：0未知 1外开门 2内开门
                openLog.setBuildName(smartLock.getBuildName());
                openLog.setCommunityName(smartLock.getCommunityName());
                openLog.setUnitName(smartLock.getUnitName());
                openLog.setMatchUserName(smartLock.getMatchUserName());
                openLog.setRoomNumber(smartLock.getRoomNumber());
                openLog.setOpenTime(DateUtil.parse(data.getUnlockTime()));
                openLog.setUserProperty(0);// 开门人性质：0未知 1承租人 2同住人
                openLog.setOpenUserName(null);//开门人姓名
                lockOpenLogRepository.save(openLog);
                return "ok";
            default:
                return "ok";
        }
    }
}
